﻿using System;
using System.Windows.Forms;
using Ast.Framework.Environment.AutofacUtil;
using Autofac;

namespace Ast.Framework.Forms
{
    public interface IFormFactory
    {
        Form Create(string type);
        Form Create(Type type);
    }

    public class FormFactory : IFormFactory
    {
        private readonly ILifetimeScope _lifetimeScope;

        public FormFactory(ILifetimeScope lifetimeScope)
        {
            _lifetimeScope = lifetimeScope;
        }

        public Form Create(string type)
        {
            var formScope = _lifetimeScope.BeginLifetimeScope(AutofacScope.Form);
            var form = formScope.ResolveNamed<Form>(type);
            form.Closed += (sender, args) => formScope.Dispose();
            return form;
        }

        public Form Create(Type type)
        {
            var formScope = _lifetimeScope.BeginLifetimeScope(AutofacScope.Form);
            var form = formScope.ResolveKeyed<Form>(type);
            form.Closed += (sender, args) => formScope.Dispose();
            return form;
        }
    }
}